package com.guo.rpc.server.handler;

import com.guo.rpc.codec.ServiceRequest;
import com.guo.rpc.codec.ServiceResponse;
import com.guo.rpc.invoke.DispatchFactory;
import com.guo.rpc.invoke.Invocation;
import com.guo.rpc.invoke.InvokeResult;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Auther: hotlove_linx
 * @Date: 2021/5/21 22:13
 * @Description:
 */
@ChannelHandler.Sharable
public class ServiceRemoteInvokeHandler extends SimpleChannelInboundHandler<ServiceRequest> {

    public static ServiceRemoteInvokeHandler INSTANCE = new ServiceRemoteInvokeHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ServiceRequest msg) throws Exception {

        Invocation invocation = getInvocation(msg);

        InvokeResult invokeResult = DispatchFactory.getInstance().dispatch(invocation);

        ServiceResponse serviceResponse = new ServiceResponse();
        serviceResponse.setResultType(invokeResult.getResultType());
        serviceResponse.setResultValue(invokeResult.getResultData());

        ctx.writeAndFlush(serviceResponse);
    }

    private Invocation getInvocation(ServiceRequest serviceRequest) {
        Invocation invocation = new Invocation();
        invocation.setInterfaceClass(serviceRequest.getInterfaceClass());
        invocation.setMethodName(serviceRequest.getMethodName());
        invocation.setParameters(serviceRequest.getArgs());
        invocation.setParameterTypes(serviceRequest.getParameterTypes());

        return invocation;
    }
}
